import actionUrls from "../../../../api/ApiUrls";
import {createDownloadForm} from "../../../js/downloadUtils"
import tiyData from "./order_detail_data";
import {webList} from "./order_funs";

function changeModelLoading(self, tiyData) {
  tiyData.tStatus.modalDeliver.isLoading = false;
  self.$nextTick(function () {
    tiyData.tStatus.modalDeliver.isLoading = true;
  });
}
/**
 * 从服务器请求订单详情
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const webOrderDetail = (self, tiyData, id) => {
  self.openCollapse = "0";
  self.isCheckedAll = false;
  tiyData.tData.orderDetail = {};
  self.$Spin.show();
  tiyData.tStatus.modalDeliver.params.selectedOrderItem = [];
  self.$apiOrder.orderDetail({
    "id": id
  }).then(function (response) {
    if (response.success) {
      let result = response.result;
      tiyData.tData.orderDetail = Object.assign({},result);
      tiyData.tData.orderDetail.receiverInfo = self.$toJson(result.receiverInfo);
      let packages = tiyData.tData.orderDetail.packages;
      if(packages.length>0){
        packages.forEach(function(item){
          item.products.forEach(function(product){ //只有已经发货状态的订单项可以修改运单号，只有出库状态订单项可以发货
            product.items.forEach(function(item){
              if(item.state != 112 && item.state != 114){
                item._disabled = true;
              }
            });
          });
        })
      }
      self.orderDetail = Object.assign({},tiyData.tData.orderDetail);
    } else {
      self.$Message.error(response.errorMessage);
    }
    self.$Spin.hide();
  });
};
/**
 * 发货
 * @param self
 * @param tiyData
 * @param type 0整单 1 拆单
 */
export const deliver = (self, tiyData, type) => {
  tiyData.tParams.deliver.waybill = "";
  tiyData.tParams.deliver.deliveryCompany = "";
  let title = '';
  switch (type) {
    case 0:
      title = "整单发货";
      break;
    case 1:
      title = "拆单发货";
      break;
    case 2:
      title = "修改运单号";
      break;
  }
  tiyData.tStatus.modalDeliver.title = title;
  tiyData.tStatus.modalDeliver.isShow = true;
  tiyData.tStatus.modalDeliver.type = type;
};

/**
 * 订单整单发货 拆单发货 修改已发货订单运单号
 * @param self
 * @param tiyData
 * @param name
 */
export const webDeliver = function (self, tiyData, name) {
  self.$refs[name].validate((valid) => {
    if (valid) {
      self.$Spin.show();
      let param = {
        id: tiyData.tData.orderDetail.id,
        waybill: tiyData.tParams.deliver.waybill,
        serialNumber: tiyData.tData.orderDetail.serialNumber,
        deliveryCompany: tiyData.tParams.deliver.deliveryCompany,
        method: tiyData.tData.orderDetail.deliveryMethod
      };
      let orderItems = '';
      if (tiyData.tStatus.modalDeliver.params.selectedOrderItem.length > 0) {
        tiyData.tStatus.modalDeliver.params.selectedOrderItem.forEach(function (item) {
          orderItems = orderItems + item.id + ',';
        });
      }
      switch (tiyData.tStatus.modalDeliver.type) {//0:订单整单发货 1:拆单发货 2:修改已发货订单运单号
        case 0:
          webOrderDeliver(self, tiyData, param);
          break;
        case 1:
          param.orderItems = orderItems;
          orderBatchDeliver(self, tiyData, param);
          break;
        case 2:
          if (orderItems != '') {
            param.orderItems = orderItems;
          }
          param.packageId = tiyData.tStatus.modalDeliver.params.packageId;
          changeWaybill(self, tiyData, param);
          break;
      }

    } else {
      changeModelLoading(self, tiyData)
    }
  });
};

function webOrderDeliver(self, tiyData, param) {
  self.$apiOrder.orderDeliver(param)
    .then(function (response) {
      changeModelLoading(self, tiyData);
      self.$Spin.hide();
      if (response.success) {
        self.$Message.success('提交成功!');
        tiyData.tStatus.modalDeliver.isShow = false;
        webOrderDetail(self, tiyData, tiyData.tData.orderDetail.id);
      } else {
        self.$Message.error(response.errorMessage);
      }
    });
}
function orderBatchDeliver(self, tiyData, param) {
  self.$apiOrder.orderBatchDeliver(param)
    .then(function (response) {
      changeModelLoading(self, tiyData);
      self.$Spin.hide();
      if (response.success) {
        self.$Message.success('提交成功!');
        tiyData.tStatus.modalDeliver.isShow = false;
        webOrderDetail(self, tiyData, tiyData.tData.orderDetail.id);
      } else {
        self.$Message.error(response.errorMessage);
      }
    });
}
function changeWaybill(self, tiyData, param) {
  self.$apiOrder.changeWaybill(param)
    .then(function (response) {
      changeModelLoading(self, tiyData);
      self.$Spin.hide();
      if (response.success) {
        self.$Message.success('提交成功!');
        tiyData.tStatus.modalDeliver.isShow = false;
        webOrderDetail(self, tiyData, tiyData.tData.orderDetail.id);
      } else {
        self.$Message.error(response.errorMessage);
      }
    });
}

/**
 * 导出配货单
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const webExportOrderBlank = (self, tiyData) => {
  self.$Spin.show();
  self.$apiOrder.exportOrderBlank({
    "id": tiyData.tParams.exportOrder.id,
    "serialNumber": tiyData.tParams.exportOrder.serialNumber,
  }).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      let msgbody = {
        "id": tiyData.tParams.exportOrder.id,
        "serialNumber": tiyData.tParams.exportOrder.serialNumber,
        "userName": tiyData.tParams.exportOrder.userName
      };
      let downloadForm = createDownloadForm(msgbody, actionUrls.URL_ORDER_DOWNLOAD_ORDER_BLANK);
      downloadForm.submit();
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};

/**
 * 导出订单发货单
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const webExportInvoice = (self, tiyData) => {
  self.$Spin.show();
  self.$apiOrder.exportInvoice({
    "id": tiyData.tParams.exportOrder.id,
    "serialNumber": tiyData.tParams.exportOrder.serialNumber,
  }).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      let msgbody = {
        "id": tiyData.tParams.exportOrder.id,
        "serialNumber": tiyData.tParams.exportOrder.serialNumber,
        "userName": tiyData.tParams.exportOrder.userName
      };
      let downloadForm = createDownloadForm(msgbody, actionUrls.URL_ORDER_DOWNLOAD_ORDER_INVOICE);
      downloadForm.submit();
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};

/**
 * 查看订单项记录
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const webItemRecord = (self, tiyData,orderItemId) => {
  self.$Spin.show();
  tiyData.tData.selectRecord.splice(0, tiyData.tData.selectRecord.length);
  self.$apiOrder.getItemRecord({
    "orderItemId": orderItemId,
  }).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      response.result.forEach(function (item) {
        tiyData.tData.selectRecord.push(item);
      });
      tiyData.tStatus.modalRecord.isShow = true
    }
  });
};

//物流跟踪
export const trackPackage = (self, tiyData) =>{
  self.$Message.loading({
    content: '正在为您查询,请稍候...',
    duration: 0
  });
  self.$apiOrder.trackPackage({
    "trackingNo":tiyData.tParams.deliver.waybill,
    "companyId":tiyData.tParams.deliver.deliveryCompany
  }).then(function(response){
    self.$Message.destroy();
    if (response.success) {
      let result = response.result;
      if(result.accessWay === 200) {
        tiyData.tStatus.modalTracking.info.splice(0,tiyData.tStatus.modalTracking.info.length);
        tiyData.tStatus.modalTracking.isShow = true;
        let info = result.trackingInfos;
        if(!info || info.length <= 0){
          tiyData.tStatus.modalTracking.info[0].acceptInfo = "没有查到快递跟踪信息！";
        } else {
          for (let i = 0; i < info.length; i++) {
            let trackInfo = {};
            trackInfo.acceptTime = info[i].acceptTime;
            trackInfo.acceptInfo = info[i].acceptInfo;
            tiyData.tStatus.modalTracking.info.push(trackInfo);
          }
        }
      } else {
        window.open(result.htmlUrl, 'newwindow',
          'height=600,width=400,top=100,left=500,toolbar=no,menubar=no,scrollbars=no, resizable=no,location=no,status=no');
      }
    } else {
      let errorMsg;
      if(response.errorMessage){
        errorMsg = response.errorMessage;
      } else {
        errorMsg = "没有查到快递跟踪信息！";
      }
      self.$Message.error({
        content: errorMsg,
        duration: 6
      });
    }

  });
}

/**
 * 查看订单项折扣
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const showItemDiscounts = (self, tiyData,orderItemId) => {
  self.$Spin.show();
  self.$apiOrder.getItemDiscount({
    "orderItemId": orderItemId,
    "isHistoryOrder": self.orderDetail.isHistoryOrder
  }).then(function (response) {
    self.$Spin.hide();
    tiyData.tData.discounts.splice(0, tiyData.tData.discounts.length);
    if (response.success) {
      response.result.forEach(function (item) {
        tiyData.tData.discounts.push(item);
      });
      tiyData.tStatus.modalDiscount.isShow = true
    }
  });
};

/**
 * 清空已经选中的订单项
 * @param self
 * @param tiyData
 */
export const clearSelectedOrderItem = (self, tiyData) => {
  for(let orderPackage of self.orderDetail.packages) {
    let checkAllName = "check_all_"+orderPackage.id;
    self.$refs[checkAllName][0].currentValue = false;
    for (let product of orderPackage.products) {
      var name = "product" + orderPackage.id + product.productCode;
      self.$refs[name][0].selectAll(false);
    }
  }
  tiyData.tStatus.modalDeliver.params.selectedOrderItem = [];
};

/**
 * 订单退款/订单项退款
 * @param self
 * @param tiyData
 */
export const refundItems = (self, tiyData) => {
  self.$refs["refund"].validate((valid) => {
    if(valid){
      let param = {
        id: tiyData.tData.orderDetail.id,
        serialNumber : tiyData.tData.orderDetail.serialNumber,
        note:tiyData.tParams.refund.note,
        refundType:tiyData.tStatus.modalRefundItems.type
      };
      if(tiyData.tStatus.modalRefundItems.type==3){
        param.acount=tiyData.tParams.refund.shippingFee
      }
      let refundAll = false; //是否整单退款
      let errorReturn = false; //订单状态错误？
      let errorMsg = "本订单不能执行此操作！";
      let refundMoney = 0; //预估退款金额
      let refundAmount = 0; //退款产品数量
      if(tiyData.tStatus.modalRefundItems.type==2){
        refundAll = true;
        param.refundAll = true;//全单退款
      }else if(tiyData.tStatus.modalRefundItems.type==1){
        if(tiyData.tData.orderDetail.itemCount == tiyData.tStatus.modalDeliver.params.selectedOrderItem.length){
          refundAll = true;
          param.refundAll = true;//全单退款
        } else {
          let itemIds = [];
          if (tiyData.tStatus.modalDeliver.params.selectedOrderItem.length > 0) {
            tiyData.tStatus.modalDeliver.params.selectedOrderItem.forEach(function (item) {
              refundMoney += item.actualPayment;
              refundAmount += item.amount;
              itemIds.push(item.id);
            });
          }
          param.itemIds = itemIds;
        }
      }

      if(errorReturn){
        self.$Message.error(errorMsg);
        self.$Spin.hide();
        return;
      }
      let refundApi;
      let message = "是否申请整单退款？";
      if(refundAll||param.refundType==3){
        refundApi = self.$apiOrder.refundOrder;
        if(param.refundType==3){
          message = "对该订单退运费:$"+ + self._.round(self.refund.shippingFee, 2);
        }
      } else {
        refundApi = self.$apiOrder.refundItems;
        message = "退款产品数量 : " + refundAmount +"件， 产品金额 : $" + self._.round(refundMoney, 2)
          + "（此金额作为参考，以后台计算金额为准）。";
      }
      self.$Modal.confirm({
        title: '退款确认',
        content: message,
        onOk: () => {
          self.$Spin.show();
          refundApi(param).then(function (response) {
            if (response.success) {
              tiyData.tStatus.modalRefundItems.isShow = false;
              self.$Message.success('提交成功!');
              webOrderDetail(self, tiyData, tiyData.tData.orderDetail.id);
            } else {
              tiyData.tStatus.modalRefundItems.isShow = false;
              self.$Message.error(response.errorMessage);
              self.$Spin.hide();
            }
          });
        }
      });
    }

  })

};


/**
 * 拆分缺货订单项
 * @param self
 * @param tiyData
 */
export const splitItem = (self, tiyData) => {
  let item = tiyData.tParams.subRefundOrderItem;
  let data ={
    "id" : item.id,
    "serialNumber" : item.serialNumber,
    "number" : item.number,
    "refundPayment" : item.refundPayment
  };
  self.$apiOrder.splitItem(data).then(function (response) {
    if (response.success) {
      self.status.modalSubRefund.isShow = false;
      self.$Message.success('拆分缺货产品成功!');
      webOrderDetail(self, tiyData, tiyData.tData.orderDetail.id);
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};

/**
 * 取消未到账订单
 * @param self
 * @param tiyData
 */
export const cancelUnconfirmedOrder = (self, tiyData) => {
  let data = {
    id: tiyData.tData.orderDetail.id,
    serialNumber : tiyData.tData.orderDetail.serialNumber
  };
  self.$apiOrder.cancelUnconfirmedOrder(data).then(function (response) {
    if (response.success) {
      self.$Message.success('取消未到账订单成功!');
      webOrderDetail(self, tiyData, tiyData.tData.orderDetail.id);
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};


/**
 * 修改运营备注
 * @param self
 * @param tiyData
 */
export const modifyInnerNote = (self, tiyData) => {
  if(!tiyData.tParams.modifyInnerNote.innerNote){
    self.$Modal.error({content:"必须录入备注内容！"});
    return;
  }

  self.$Spin.show();
  self.$apiOrder.addInnerNote(tiyData.tParams.modifyInnerNote).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      self.$Message.success('添加运营备注成功!');
      self.orderDetail.innerNote = tiyData.tParams.modifyInnerNote.innerNote;
    } else {
      let error = "添加运营备注失败！";
      if(response.errorMessage){
        error += response.errorMessage;
      }
      self.$Message.error(error);
    }
  });
};

/**修改重要说明
 * @param self
 * @param tiyData
 * */
export const modifyImportantNote = (self, tiyData) => {
  self.$Spin.show();
  self.$apiOrder.modifyImportantNote(tiyData.tParams.modifyImportantNote).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      self.$Message.success('修改重要说明成功!');
      self.orderDetail.importantNote = tiyData.tParams.modifyImportantNote.importantNote;
    } else {
      let error = "修改重要说明失败！";
      if(response.errorMessage){
        error += response.errorMessage;
      }
      self.$Message.error(error);
    }
  });
};

/**
 * 查看订单款项记录
 * @param self
 * @param tiyData
 * @param orderId
 * @returns {Array}
 */
export const getPaymentRecords = (self, tiyData, orderId) => {
  self.$Spin.show();
  self.$apiOrder.getOrderPaymentRecord({
    "id": orderId,
    "isHistoryOrder": self.orderDetail.isHistoryOrder
  }).then(function (response) {
    self.$Spin.hide();
    tiyData.tData.orderPaymentRecords.splice(0, tiyData.tData.orderPaymentRecords.length);
    if (response.success) {
      response.result.forEach(function (item) {
        tiyData.tData.orderPaymentRecords.push(item);
      });
      tiyData.tStatus.modalPaymentRecordShow = true;
    } else {
      self.$Message.error("查询订单款项记录失败！" + response.errorMessage);
    }
  });
};

/**
 * 查看订单折扣
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const showOrderDiscounts = (self, tiyData,orderId) => {
  self.$Spin.show();
  self.$apiOrder.getOrderDiscount({
    "orderId": orderId,
    "isHistoryOrder": self.orderDetail.isHistoryOrder
  }).then(function (response) {
    self.$Spin.hide();
    tiyData.tData.discounts.splice(0, tiyData.tData.discounts.length);
    if (response.success) {
      response.result.forEach(function (item) {
        // var discountItem = {};
        tiyData.tData.discounts.push(item);
      });
      tiyData.tStatus.modalDiscount.isShow = true
    }
  });
};

/**
 * 查看产品货源信息
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const showProductSupply = (self, tiyData, productId) => {
  self.$Spin.show();
  tiyData.tData.productSupplyList.splice(0, tiyData.tData.productSupplyList.length);
  self.$apiProduct.getProductSupplys({
    "productId": productId,
  }).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      response.result.forEach(function (item) {
        tiyData.tData.productSupplyList.push(item);
      });
      tiyData.tStatus.modalSupply.isShow = true
    } else {
      self.$Message.error("查询产品货源失败。" + response.errorMessage);
    }

  });
};

/**
 * 查看订单记录
 * @param self
 * @param tiyData
 * @param orderId
 * @returns {Array}
 */
export const webOrderRecord = (self, tiyData,orderId) => {
  self.$Spin.show();
  tiyData.tData.selectRecord.splice(0, tiyData.tData.selectRecord.length);
  self.$apiOrder.getOrderRecord({
    "orderId": orderId,
    "isHistoryOrder": self.orderDetail.isHistoryOrder
  }).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      response.result.forEach(function (item) {
        tiyData.tData.selectRecord.push(item);
      });
      tiyData.tStatus.modalRecord.isShow = true
    }
  });
};


/**
 * 查看包裹记录
 * @param self
 * @param tiyData
 * @param orderId
 * @param packageId
 * @returns {Array}
 */
export const webPackageRecord = (self, tiyData,orderId, packageId) => {
  self.$Spin.show();
  tiyData.tData.selectRecord.splice(0, tiyData.tData.selectRecord.length);
  self.$apiOrder.getPackageRecord({
    "orderId": orderId,
    "packageId": packageId,
    "isHistoryOrder": self.orderDetail.isHistoryOrder
  }).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      response.result.forEach(function (item) {
        tiyData.tData.selectRecord.push(item);
      });
      tiyData.tStatus.modalRecord.isShow = true
    }
  });
};

/**
 * 设置用户拒付
 * @param self
 * @param tiyData
 */
export const refusePayment = (self, tiyData) => {
  let data = {
    id: tiyData.tData.orderDetail.id,
    serialNumber : tiyData.tData.orderDetail.serialNumber,
    poundage: tiyData.tParams.refusePayment.poundage
  };
  self.$apiOrder.setRefusePayment(data).then(function (response) {
    if (response.success) {
      self.$Message.success('设置订单用户拒付成功!');
      webOrderDetail(self, tiyData, tiyData.tData.orderDetail.id);
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};

/**导出标准的发票*/
export const exportStandardInvoice = (self, tiyData) => {
    self.$Spin.show();
    self.$apiOrder.exportStandardInvoice({
      "id": tiyData.tParams.exportInvoice.orderId,
      "itemStates": tiyData.tParams.exportInvoice.selectedOrderItemStates,
      "companyName": tiyData.tParams.exportInvoice.companyName,
      "isHistoryOrder": tiyData.tData.orderDetail.isHistoryOrder
    }).then(response => {
      self.$Spin.hide();
      tiyData.tStatus.modalExportInvoice.isShow = false;
      if (response.success) {
        let msgBody = {
          "id": tiyData.tParams.exportInvoice.orderId,
        };
        let downloadForm = createDownloadForm(msgBody, actionUrls.URL_ORDER_DOWNLOAD_ORDER_STANDARD_INVOICE);
        downloadForm.submit();
      } else {
        self.$Message.error(response.errorMessage);
      }
    });
  }

/**
 * 查询支付信用卡详情
 * @param self
 * @param tiyData
 */
export const getCreditCard = (self, tiyData) => {
  self.$Spin.show();
  if(tiyData.tData.orderDetail.creditCard){
    delete tiyData.tData.orderDetail.creditCard;
  }
  self.$apiOrder.getCreditCart({
    "orderId": tiyData.tData.orderDetail.id
  }).then(response => {
    self.$Spin.hide();
    if (response.success) {
      tiyData.tData.orderDetail.creditCard = response.result;
      self.orderDetail = Object.assign({},tiyData.tData.orderDetail);
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
}

/**
 * 确认线下收款
 * @param self
 * @param tiyData
 */
export const confirmOffline = (self, tiyData) => {
  self.$refs["confirmOffline"].validate((valid) => {
    if (valid) {
      self.$Spin.show();
      let data = tiyData.tParams.confirmOffline;
      self.$apiOrder.confirmOffline(data).then(response => {
        self.$Spin.hide();
        if (response.success) {
          tiyData.tStatus.modalConfirmOffline.isShow = false;
          self.$Message.success('确认订单线下收款成功!');
          webOrderDetail(self, tiyData, tiyData.tData.orderDetail.id);
        } else {
          self.$Message.error(response.errorMessage);
        }
      });
    } else {
      changeModelLoading(self, tiyData);
    }
  });
};

/**
 * 挂起线下收款订单
 * @param self
 * @param tiyData
 */
export const pendingOffline = (self, tiyData) => {
  self.$Spin.show();
  let orders = [];
  let order = {"id": tiyData.tData.orderDetail.id, "serialNumber": tiyData.tData.orderDetail.serialNumber};
  orders.push(order);
  let data = {"orders" : orders, "isConfirm" : false}
  self.$apiOrder.confirmOrders(data).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      self.$Message.success('线下收款订单挂起成功!');
      webOrderDetail(self, tiyData, tiyData.tData.orderDetail.id);
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};
